package light.head.controller.sys;


import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.sys.MessageDAO;
import light.head.dao.sys.MessageReceiveDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.framework.utils.MailUtils;
import light.head.model.FileInfo;
import light.head.model.Message;
import light.head.model.MessageAnnex;
import light.head.model.MessageReceive;
import light.head.model.MessageReceivePK;
import light.head.model.UserInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping(value = Url.C_MESSAGE)
public class MessageController extends SupporterController {
	private final static String upload_path = "upload/messageAnnex/";
	private final static String message_photo_path = "upload/messagePhoto/";
	private final static String message_file_path = "upload/messageFile/";

	private MessageDAO messageDAO;
	private MessageReceiveDAO messrDAO;
	private OrganDAO organDAO;

	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.MESSAGE_INIT);
	}

	@RequestMapping(Url.QUERY)
	public ModelAndView query(String type, HttpServletRequest request, HttpServletResponse response) {
		PageBean pb = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.TITLE, Parm.START, Parm.END, Parm.IV);
		map.put(Parm.TYPE, type);

		if (RESULT.SUCCESS == messageDAO.findByMap(cu_code(request), map, pb)) {
			request.setAttribute(Parm.PAGE_BEAN, pb);
		}
		if (type.equals(Sys.S_ONE)) {
			List<Integer> codes = null;
			if (null != pb.getResultList() && pb.getResultList().size() > 0) {
				codes = new ArrayList<Integer>();
				for (Object o : pb.getResultList()) {
					codes.add(((Message)o).getCode());
				}
				List<Object[]> ivs = messageDAO.findOpenStatus(codes, cu_code(request));
				request.setAttribute(Parm.LIST, ivs);
			}
			return new ModelAndView(Url.MESSAGE_LIST1);
		} else if (type.equals(Sys.S_TWO)) {
			return new ModelAndView(Url.MESSAGE_LIST2);
		} else if (type.equals(Sys.S_THREE))
			return new ModelAndView(Url.MESSAGE_LIST3);
		
		return null;
	}
	
	// @Transactional
	@RequestMapping(Url.SEND)
	public void send(String uuid, Message message, HttpServletRequest request, HttpServletResponse response) {
		if (null == message) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		message.setCt(new Date());
		message.setCu(cu_code(request));
		message.setDeleted(false);

		String tt = message.getContent();
		if (messageDAO.add(message) == RESULT.SUCCESS) {
			if (null != message.getAnList() && message.getAnList().size() > 0) {
				for (MessageAnnex ma : message.getAnList()) {
					if (isNotNull(ma.getName()) && isNotNull(ma.getUuid()) && isNotNull(ma.getExt()) && null != ma.getSize()) {
						ma.setMc(message.getCode());
						ma.setDeleted(false);
						messageDAO.add(ma);
					}
				}
			}
			
			tt += "该信息由" + cu_realName(request) + "发出，有包含附件，请到" + upload_path +"下载";
		}

		/******************* 收件人 *******************/
		String[] runs = request.getParameterValues(Parm.RUN);
		String[] emails = request.getParameterValues(Parm.EMAIL);
		
		if (null != runs && runs.length > 0) {
			MessageReceive temp = null;
			for (int i = 0; i < runs.length; i ++) {
				if (isNotNull(runs[i])) {
					temp = new MessageReceive();
					temp.setMc(message.getCode());
					temp.setRuc(Integer.parseInt(runs[i]));
					temp.setIv(false);
					temp.setDeleted(false);
					
				
					
					if (messrDAO.add(temp) == RESULT.SUCCESS && isNotNull(emails[i])) {
						MailUtils.send(ConfigParm.getMessageServer(),
								ConfigParm.getMessageUname(),
								ConfigParm.getMessagePwd(), emails[i],
								ConfigParm.getMessageUname(),
								ConfigParm.getMessageName(), message.getTitle(), tt, null);
					}
				}
			}
			print(response, Msg.SUCCESS);
		} else {
			print(response, Msg.ERROR);
		}
	}

	/**
	 *上传一张图片和一个文件
	 * 
	 */
	@Transactional
	@RequestMapping(Url.UPLOAD)
	public void upload(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile pohto = multipartRequest.getFile(Parm.UPLOAD);
		String type = request.getParameter(Parm.TYPE);
		String name = pohto.getOriginalFilename();

		if (isNotNull(name)) {
			String ext = name.substring(name.lastIndexOf(Sys.DOT) + 1);
			if (!ext.toUpperCase().equals(Sys.JPG)
					&& !ext.toUpperCase().equals(Sys.GIF)
					&& !ext.toUpperCase().equals(Sys.JPEG)
					&& !ext.toUpperCase().equals(Sys.BMP)
					&& !ext.toUpperCase().equals(Sys.PNG)
					&& !ext.toUpperCase().equals(Sys.XLSX)
					&& !ext.toUpperCase().equals(Sys.XLS)
					&& !ext.toUpperCase().equals(Sys.DOCX)
					&& !ext.toUpperCase().equals(Sys.DOC)
					&& !ext.toUpperCase().equals(Sys.PDF)
					&& !ext.toUpperCase().equals(Sys.PPT)
					&& !ext.toUpperCase().equals(Sys.RAR)
					&& !ext.toUpperCase().equals(Sys.ZIP)) {
				print(response, Msg.FILE_TYPE_ERROR);
				return;
			}
			name = name.substring(0, name.lastIndexOf(Sys.DOT));

			UUID u = UUID.randomUUID();
			String uuid = u.toString().replace("-", "");
			String path = (type.equals(Sys.FILE) ? message_file_path
					: message_photo_path) + uuid + Sys.DOT + ext;
			String savePath = ConfigParm.getProjectPath() + path;
			FileOutputStream fo;
			int size = 0;

			try {
				fo = new FileOutputStream(savePath);
				size = pohto.getBytes().length;
				fo.write(pohto.getBytes());
				fo.close();
			} catch (Exception e) {
				print(response, Msg.ERROR);
				e.printStackTrace();
				throw new RuntimeException();
			}

			FileInfo f = new FileInfo();
			f.setDeleted(false);
			f.setExt(ext);
			f.setName(name);
			f.setUuid(uuid);
			f.setCt(new Date());
			if (type.equals(Sys.FILE)) {
				f.setType(Sys.B_ONE);
				f.setModule(Parm.MESSAGE_FILE);
			} else {
				f.setType(Sys.B_TWO);
				f.setModule(Parm.MESSAGE_PHOTO);
			}

			f.setCu(cu_code(request));
			f.setOc(cu_organCode(request));
			f.setSize(size);
			messageDAO.add(f);

			StringBuffer result = new StringBuffer();
			result.append("<script type=\"text/javascript\">");
			if (isNotNull(path)) {
				result.append("window.parent.CKEDITOR.tools.callFunction(" + request.getParameter("CKEditorFuncNum") + ", '" + path + "')");
				result.append("</script>");
				result.append(path);
			} else {
				result.append("alert(\"上传失败，文件类型需要jpg、gif或png\")");
				result.append("</script>");
			}
			response.setHeader("Content-Type", "text/html; charset=UTF-8");
			print(response, result.toString());

		} else {
			print(response, Msg.ERROR);
		}
	}

	/**
	 * 上传多张图片和多个文件
	 */
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(Integer code, HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequest.getFiles("files");

		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {

			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;

			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				//System.out.println(mf.getOriginalFilename() + "--" + mf.getName());
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG)
							&& !ext.toUpperCase().equals(Sys.GIF)
							&& !ext.toUpperCase().equals(Sys.JPEG)
							&& !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)
							&& !ext.toUpperCase().equals(Sys.XLSX)
							&& !ext.toUpperCase().equals(Sys.XLS)
							&& !ext.toUpperCase().equals(Sys.DOCX)
							&& !ext.toUpperCase().equals(Sys.DOC)
							&& !ext.toUpperCase().equals(Sys.PDF)
							&& !ext.toUpperCase().equals(Sys.PPT)
							&& !ext.toUpperCase().equals(Sys.RAR)
							&& !ext.toUpperCase().equals(Sys.ZIP)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));

					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = upload_path + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;
					
				
					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}

					FileInfo f = new FileInfo();
					f.setDeleted(false);
					f.setExt(ext);
					f.setName(name);
					f.setCt(new Date());
					f.setType(isImg(ext) ? Sys.B_TWO : Sys.B_ONE);
					f.setModule(Parm.MESSAGE_ANNEX);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					messageDAO.add(f);

					result.append("{\"name\":\"" + name + "\",\"uuid\":\"" + uuid + "\",\"ext\":\"" + ext + "\",\"size\":\"" + size + "\",\"path\":\"" + uuid + Sys.DOT + ext + "\"},");
				}
			}

			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}

	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request,HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (isNotNull(code)) {
			Message ms = messageDAO.get(Integer.parseInt(code));
			request.setAttribute(Parm.MESSAGE, ms);
		}
		return new ModelAndView(Url.MESSAGE_EDIT);
	}
	
	/**
	 * 收到的消息详情
	 *
	 */
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(Integer code, Integer ruc, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			Message message = messageDAO.get(code);
			List<MessageAnnex> maList = messageDAO.findAnnexByMeesgCode(code);
			
			MessageReceivePK mrpk = new MessageReceivePK();
			mrpk.setMc(code);
			mrpk.setRuc(cu_code(request));
			MessageReceive messr = messrDAO.get(mrpk);
			if (null == messr.getIv() || !messr.getIv()) {
				messr.setIv(true);
				messrDAO.upd(messr);
			}
			
			request.setAttribute(Parm.MESSAGE, message);
			request.setAttribute(Parm.LIST_1, maList);
		}
		return new ModelAndView(Url.MESSAGE_DETAIL);
	}
	/**
	 * 标记状态
	 */
	@RequestMapping(Url.STATE)
	public void state(Integer code, HttpServletRequest request, HttpServletResponse response){
		if(null != code){
			MessageReceivePK mrpk = new MessageReceivePK();
			mrpk.setMc(code);
			mrpk.setRuc(cu_code(request));
			MessageReceive messr = messrDAO.get(mrpk);
			if (null == messr.getIv()) {
				print(response, Msg.NOT_FIND);
				return;
			}
			messr.setIv(!messr.getIv());
			if (messageDAO.upd(messr) == RESULT.SUCCESS)
				print(response, Msg.SUCCESS);
			else
			print(response, Msg.ERROR);
		}
		
	}
	/**
	 * 改变所有状态
	 */
	@RequestMapping(Url.READ)
	public void read(HttpServletRequest request, HttpServletResponse response){
		RESULT result = RESULT.ERROR;
		List<MessageReceive> mrList = messrDAO.findByCu(cu_code(request));
		if(null != mrList && mrList.size() != 0){
			for (MessageReceive messr : mrList) {
				messr.setIv(true);
				result = messrDAO.upd(messr);
			}
		}
		if (result== RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
		print(response, Msg.ERROR);
		
	}
	
	/**
	 * 发送的消息详情
	 *
	 */
	@RequestMapping(value = Url.DETAIL1)
	public ModelAndView detail1(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			Message msg = messageDAO.get(code);
			List<MessageAnnex> maList = messageDAO.findAnnexByMsgCode(code);
			List<MessageReceive> mrList = messrDAO.findByMessageCode(code);
			
			request.setAttribute(Parm.MESSAGE, msg);
			request.setAttribute(Parm.LIST_2, maList);
			request.setAttribute(Parm.LIST_1, mrList);
		}
		return new ModelAndView(Url.MESSAGE_DETAIL1);
	}

	/*
	 * 回复邮件
	 */
	@RequestMapping(value = Url.REPLY)
	public ModelAndView reply(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			Message message = messageDAO.get(code);
			if (null != message) {
				message.setTitle("Re:" + message.getTitle());
				message.setCode(null);
				
				MessageReceive mr = new MessageReceive();
				mr.setRuc(message.getCu());
				mr.setRun(message.getCun());
				
				request.setAttribute(Parm.MESSAGE, message);
				request.setAttribute(Parm.MR, mr);
			}
		}
		return new ModelAndView(Url.MESSAGE_EDIT);
	}
	/**
	 * 删除接收的信息
	 */
	@RequestMapping(Url.DELETE1)
	public void delete1(Integer code, HttpServletRequest request, HttpServletResponse response) {
		if (null != code) {
			MessageReceivePK mrpk = new MessageReceivePK();
			mrpk.setMc(code);
			mrpk.setRuc(cu_code(request));
			
			MessageReceive mr = messrDAO.get(mrpk);
			
			if (null == mr) {
				print(response, Msg.NOT_FIND);
			} else {
				Message m = messageDAO.get(code);
				m.setDeleted(false);
				messrDAO.upd(m);
				mr.setDeleted(false);
				print(response, messrDAO.upd(mr).toString().toLowerCase());
			}
		} else {
			print(response, Msg.PARAMETER_ERROR);
		}
	}
	/**
	 * 删除接收的信息
	 */
	@RequestMapping(Url.DELETE2)
	public void delete2(Integer code, HttpServletRequest request, HttpServletResponse response) {
		if (null != code) {
			MessageReceivePK mrpk = new MessageReceivePK();
			mrpk.setMc(code);
			mrpk.setRuc(cu_code(request));
			
			MessageReceive mr = messrDAO.get(mrpk);
			
			if (null == mr) {
				print(response, Msg.NOT_FIND);
			} else {
				
				mr.setDeleted(true);
				print(response, messrDAO.upd(mr).toString().toLowerCase());
			}
		} else {
			print(response, Msg.PARAMETER_ERROR);
		}
	}

	/**
	 * 彻底删除
	 */
	@RequestMapping(value = Url.DELETE)
	public void delete(HttpServletRequest request, HttpServletResponse response)throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}

		if (messageDAO.del(Integer.parseInt(code)) == RESULT.SUCCESS) {
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}
	/**
	 * 删除自己发送的消息
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = Url.RECYCLE)
	public void recycle(HttpServletRequest request, HttpServletResponse response)throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Message message = messageDAO.get(Integer.parseInt(code));
		if (null == message) {
			print(response, Msg.NOT_FIND);
			return;
		}

		message.setDeleted(true);
		if (messageDAO.update(message) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
	}

	@RequestMapping(value = Url.UN_SHIELD)
	public void unshield(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		if (!isNotNull(code)) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Message m = messageDAO.get(Integer.parseInt(code));
		if (null == m) {
			print(response, Msg.NOT_FIND);
			return;
		}

		m.setDeleted(false);
		if (messageDAO.upd(m) == RESULT.SUCCESS)
			print(response, Msg.SUCCESS);
		else
			print(response, Msg.ERROR);
		
	}

	/**
	 * 查询接收人
	 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidUserInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String suc = request.getParameter(Parm.SUC);
		if (isNotNull(suc)) {
			List<UserInfo> list = messageDAO.findUserByCodes(suc);
			request.setAttribute(Parm.LIST, list);
		}
		return new ModelAndView(Url.MESSAGE_USER_INIT);
	}

	@RequestMapping(Url.AID_LIST)
	public ModelAndView aidUserList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.REAL_NAME, Parm.SUC);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == messageDAO.findUser(organDAO.getSonCodeList(oc),map, pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.MESSAGE_USER_LIST);
	}
	
	
	
	
	private boolean isImg(String ext) {
		if (!isNotNull(ext))
			return false;
		if (ext.toUpperCase().equals(Sys.JPG)
				|| ext.toUpperCase().equals(Sys.GIF)
				|| ext.toUpperCase().equals(Sys.JPEG)
				|| ext.toUpperCase().equals(Sys.BMP)
				|| ext.toUpperCase().equals(Sys.PNG)) {
			return true;
		}
		return false;
	}
	
	
	@RequestMapping(Url.LOAD_TOTAL)
	public void loadTotal(HttpServletRequest request, HttpServletResponse response) {
		if (null == cu_code(request)) {
			print(response, Msg.NO_LOGIN);
			return;
		}
		
		Integer total = messageDAO.getTotalByUserCode(cu_code(request));
		print(response, total.toString());
	}
	
	
	
	
	@Autowired
	public void setMessageDAO(MessageDAO messageDAO) {
		this.messageDAO = messageDAO;
	}
	
	@Autowired
	public void setMessrDAO(MessageReceiveDAO messrDAO) {
		this.messrDAO = messrDAO;
	}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
	
}
